document.addEventListener('DOMContentLoaded', () => {
    // 状态元素
    const statusElement = document.getElementById('status');
    const videoElement = document.getElementById('video');
    
    // 控制按钮
    const btnUp = document.getElementById('btn-up');
    const btnDown = document.getElementById('btn-down');
    const btnLeft = document.getElementById('btn-left');
    const btnRight = document.getElementById('btn-right');
    const btnStop = document.getElementById('btn-stop');
    
    // 配置滑块
    const speedSlider = document.getElementById('speed-slider');
    const distanceSlider = document.getElementById('distance-slider');
    const speedValue = document.getElementById('speed-value');
    const distanceValue = document.getElementById('distance-value');
    
    // 传感器显示
    const distanceDisplay = document.getElementById('distance');
    const temperatureDisplay = document.getElementById('temperature');
    const speedLimitDisplay = document.getElementById('speed-limit');
    
    // WebRTC变量
    let pc = null;
    let dc = null;
    const socket = io('http://<EXYNOS_IP>:8080');
    
    // 连接状态
    let isConnected = false;
    
    // 初始化WebRTC连接
    async function initWebRTC() {
        if (isConnected) return;
        
        setStatus('connecting', '连接中...');
        
        try {
            pc = new RTCPeerConnection({
                iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
            });
            
            // 处理视频流
            pc.ontrack = event => {
                if (event.track.kind === 'video') {
                    videoElement.srcObject = event.streams[0];
                }
            };
            
            // 创建数据通道
            dc = pc.createDataChannel('control', {
                ordered: true,
                maxRetransmits: 3
            });
            
            dc.onopen = () => {
                setStatus('connected', '已连接');
                isConnected = true;
            };
            
            dc.onclose = () => {
                setStatus('disconnected', '连接断开');
                isConnected = false;
            };
            
            dc.onmessage = handleDataMessage;
            
            // 创建Offer
            const offer = await pc.createOffer();
            await pc.setLocalDescription(offer);
            
            // 通过信令服务器发送Offer
            socket.emit('offer', offer);
            
            // 处理ICE候选
            pc.onicecandidate = ({ candidate }) => {
                if (candidate) {
                    socket.emit('candidate', candidate);
                }
            };
            
        } catch (error) {
            console.error('WebRTC初始化失败:', error);
            setStatus('disconnected', '连接失败');
        }
    }
    
    // 处理来自车辆的数据消息
    function handleDataMessage(event) {
        try {
            const data = JSON.parse(event.data);
            
            if (data.type === 'sensors') {
                // 更新传感器数据
                distanceDisplay.textContent = data.data.dist.toFixed(1);
                temperatureDisplay.textContent = data.data.temp.toFixed(1);
                speedLimitDisplay.textContent = data.data.speed_limit;
            }
        } catch (e) {
            console.warn('无效数据:', event.data);
        }
    }
    
    // 发送控制命令
    function sendCommand(key) {
        if (!isConnected || !dc) return;
        
        const command = {
            type: 'control',
            key: key,
            timestamp: Date.now()
        };
        
        dc.send(JSON.stringify(command));
    }
    
    // 发送配置更新
    function sendConfig() {
        if (!isConnected || !dc) return;
        
        const config = {
            type: 'config',
            max_speed: parseInt(speedSlider.value),
            safe_distance: parseInt(distanceSlider.value)
        };
        
        dc.send(JSON.stringify(config));
    }
    
    // 设置状态显示
    function setStatus(statusClass, text) {
        statusElement.textContent = text;
        statusElement.className = '';
        statusElement.classList.add(statusClass);
    }
    
    // 事件监听器
    btnUp.addEventListener('mousedown', () => sendCommand('ArrowUp'));
    btnDown.addEventListener('mousedown', () => sendCommand('ArrowDown'));
    btnLeft.addEventListener('mousedown', () => sendCommand('ArrowLeft'));
    btnRight.addEventListener('mousedown', () => sendCommand('ArrowRight'));
    btnStop.addEventListener('mousedown', () => sendCommand('Space'));
    
    // 触摸设备支持
    btnUp.addEventListener('touchstart', (e) => {
        e.preventDefault();
        sendCommand('ArrowUp');
    });
    
    // 释放按钮时停止
    const buttons = [btnUp, btnDown, btnLeft, btnRight, btnStop];
    buttons.forEach(btn => {
        btn.addEventListener('mouseup', () => sendCommand('Space'));
        btn.addEventListener('mouseleave', () => sendCommand('Space'));
        btn.addEventListener('touchend', () => sendCommand('Space'));
    });
    
    // 键盘控制
    document.addEventListener('keydown', (e) => {
        if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
            e.preventDefault();
            sendCommand(e.key);
        }
    });
    
    document.addEventListener('keyup', (e) => {
        if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
            sendCommand('Space');
        }
    });
    
    // 配置滑块事件
    speedSlider.addEventListener('input', () => {
        speedValue.textContent = speedSlider.value;
        sendConfig();
    });
    
    distanceSlider.addEventListener('input', () => {
        distanceValue.textContent = distanceSlider.value;
        sendConfig();
    });
    
    // 初始化连接
    initWebRTC();
    
    // 处理信令
    socket.on('answer', async (answer) => {
        if (!pc) return;
        try {
            await pc.setRemoteDescription(answer);
        } catch (e) {
            console.error('设置远程描述失败:', e);
        }
    });
    
    socket.on('candidate', async (candidate) => {
        if (!pc) return;
        try {
            await pc.addIceCandidate(candidate);
        } catch (e) {
            console.warn('添加ICE候选失败:', e);
        }
    });
    
    socket.on('connect_error', () => {
        setStatus('disconnected', '服务器连接失败');
    });
});